﻿using Furion.Logging;
using Furion;

using NetTaste;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SKIT.FlurlHttpClient.Wechat.Api;
using Conversive.PHPSerializationLibrary;
using Newtonsoft.Json;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using Furion.Schedule;
using Furion.TimeCrontab;
using Serilog;

namespace MqttClient.Jobs
{
    // 每天20:0分 
    [Cron("0 01 20 * * *", CronStringFormat.WithSeconds)]
    //[PeriodSeconds(3)]
    [JobDetail(jobId: "缴费监测", description: "每天20点1分执行", GroupName = "系统", Concurrent = false)]
    public class JiaofeichcekJob : IJob
    {
        private readonly IDatabase dbredis;
        public string server = "https://weixin.tslexunbao.com";
        //        ConnectionMultiplexer redis;
        string pkey = "easywechat.kernel.access_token*";
        string key = "easywechat.kernel.access_token";
        PhpSerializer ps = new PhpSerializer();
        bool send = false;
        /// <summary>
        ///  微信token
        /// </summary>
        private string token;
        private readonly WechatApiClientOptions options;
        private readonly ILogger loger;

        public JiaofeichcekJob(ILogger loger)
        {
            options = new WechatApiClientOptions()
            {
                AppId = "wx42a8bcc9d53bcf3b",
                AppSecret = "673321d209f6c3e3b4d8d9eb6fce56a6",
            };
            ConnectionMultiplexer redis = App.GetService<ConnectionMultiplexer>();
            var server = redis.GetServer("127.0.0.1", 6379);
            dbredis = redis.GetDatabase(0);

            foreach (var key in server.Keys(pattern: pkey))
            {
                //  Console.WriteLine(key);
                this.key = key;
                Console.WriteLine(key);
            }

            this.loger = loger;
        }
        Task IJob.ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
        {
            Console.WriteLine("Jiaofeichcek");
            loger.Warning("Jiaofeichcek");

          
            // var services = scope.ServiceProvider;
            try
            {
                var str = (dbredis.StringGet(key));
                if (!String.IsNullOrEmpty(str))
                {
                    var t = (Dictionary<object, object>)ps.Deserialize(str);
                    if (t.ContainsKey("access_token"))
                    {
                        token = t["access_token"].ToString();
                        // Console.WriteLine(token);

                        Console.ForegroundColor = ConsoleColor.White;

                        var wxtz = App.GetService<WeixinTongzhi>();// services.GetService<WeixinTongzhi>();
                        using (var unsend = wxtz.getEndsend())
                        {

                            foreach (DataRow kaoqin in unsend.Rows)
                            {
                                try
                                {

                                    using (var untz = wxtz.getDaoqiTongzhi(kaoqin["user_id"].ToString()))
                                    {

                                        foreach (DataRow guanzhu in untz.Rows)
                                        {

                                            BuildXufeiMsg(token, kaoqin, guanzhu);




                                        }


                                    }


                                }
                                catch (Exception e)
                                {
                                    loger.Error($"{e.Message} ");

                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.WriteLine(e.Message);
                                    Console.ForegroundColor = ConsoleColor.White;
                                }

                            }

                        }
                        wxtz.close();
                    }
                }

            }
            catch (Exception e)
            {
                loger.Error($"微信通知 失败 {e.Message} ");
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("微信通知 失败 " + e.Message);
            }

            return Task.CompletedTask;

        }

        /// <summary>
        /// 发送到期续费通知
        /// </summary>
        /// <param name="token"></param>
        /// <param name="stu"></param>
        /// <param name="jiazhang"></param>
        private void BuildXufeiMsg(string token, DataRow stu, DataRow jiazhang)
        {


            CgibinMessageTemplateSendRequest tplr = new CgibinMessageTemplateSendRequest();
            tplr.TemplateId = TplIds.交费提醒;
            tplr.Data = new Dictionary<string, CgibinMessageTemplateSendRequest.Types.DataItem>();
            string msg = "的移动平安校园服务急需续费";



            // 头
            tplr.Data.Add("first", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = $"亲爱的{jiazhang["username"]}家长, {jiazhang["username"]}同学{msg}", Color = "#173177" });
            // 姓名
            tplr.Data.Add("keyword1", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = jiazhang["username"].ToString(), Color = "#173177" });
            // 时间
            tplr.Data.Add("keyword2", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = "进出校消息提醒/公共电话/成绩分析/直饮水等", Color = "#173177" });
            // 地点
            tplr.Data.Add("keyword3", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = "90元/年或开通移动手机扣费10元/月", Color = "#173177" });
            // 备注
            tplr.Data.Add("remark", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = "为了不影响您的使用，请尽快续费，如有疑问咨询客服。", Color = "#ff0000" });
#if DEBUG
            tplr.ToUserOpenId = "oyXHL0qFna08ZW-mnlDUiYEjOMW8";
#else
            tplr.ToUserOpenId = jiazhang["oauth_id"].ToString();
#endif
            tplr.AccessToken = token;
            tplr.Url = "https://weixin.tslexunbao.com/product/index/17?uid=" + stu["user_id"];


            // Console.WriteLine("开始发送");
            var client = new WechatApiClient(options);
            client.ExecuteCgibinMessageTemplateSendAsync(tplr).ContinueWith((res =>
            {
                Console.WriteLine($"续费 {DateTime.Now.ToString("yyyy-MM-dd HH:mm")} {stu["clname"]} {jiazhang["username"]} {tplr.ToUserOpenId}->{stu["user_id"]}  {res.Result.ErrorMessage}");

                loger.Error($"续费  {DateTime.Now.ToString("yyyy-MM-dd HH:mm")} {stu["clname"]} {jiazhang["username"]}  {JsonConvert.SerializeObject(tplr)}{tplr.ToUserOpenId}->{stu["user_id"]}  {res.Result.ErrorMessage}");
            }));

        }

    }


}
